package com.example.bgmachine.bgmachine.sets;

import android.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.bgmachine.bgmachine.ContentInfor;
import com.example.bgmachine.bgmachine.R;
import com.example.bgmachine.bgmachine.commons.ConfigParams;
import com.example.bgmachine.bgmachine.databases.MyDatabaseInfor;
import com.example.bgmachine.bgmachine.goods.HomepageLeftMenuItemData;
import com.example.bgmachine.bgmachine.goods.HomepageListLeftMenuAdapter;
import com.example.bgmachine.bgmachine.goods.LeftSelectindex;
import com.example.bgmachine.bgmachine.homes.HomePages;
import com.example.bgmachine.bgmachine.homes.MerilData;
import com.example.bgmachine.bgmachine.martirelpro.HomepageMertrielProgressItemData;
import com.example.bgmachine.bgmachine.orders.OrderContentAdapter;
import com.example.bgmachine.bgmachine.orders.OrderContentData;
import com.example.bgmachine.bgmachine.popupviews.PasswordEdit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SetsFragment extends Fragment {

    private RelativeLayout sets_bottom_right_clear_relative_layout = null;
    private RelativeLayout sets_bottom_right_check_relative_layout = null;
    private RelativeLayout sets_bottom_right_material_relative_layout = null;
    private RelativeLayout sets_bottom_right_drain_relative_layout = null;
    private RelativeLayout sets_bottom_right_pin_relative_layout = null;
    private RelativeLayout sets_bottom_right_pwd_relative_layout = null;

    private Button set_pwds_ok_btn = null;
    private PasswordEdit password_passwordedit_center_old_pwds = null;
    private PasswordEdit password_passwordedit_center_new_1_pwds = null;
    private PasswordEdit password_passwordedit_center_new_2_pwds = null;

    private Context mContext = null;
    private ListView sets_bottom_left_listvew = null;
    private ArrayList<SetsLeftMenuItemData> mSetsLeftMenuItemData = new ArrayList<SetsLeftMenuItemData>();
    private SetsListLeftMenuAdapter mSetsListLeftMenuAdapter = null;


    private HashMap<Integer, Integer> mpinsEmptynfors = new HashMap<Integer, Integer>();
    private Handler mTimeShowHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (mpinsEmptynfors.size() > 0) {
                        String namea = "";
                        if (mEmptyType == 0) {
                            namea = mContext.getResources().getString(R.string.sets_fragment_layout_feed_tip_text);
                        } else {
                            namea = mContext.getResources().getString(R.string.sets_fragment_layout_empty_tip_text);

                        }
//                        if(mpinsEmptynfors.size() > 6){
//                            mpinsEmptynfors.clear();
//                            mEmptySetAdapter.notifyDataSetChanged();
//                            Toast.makeText(mContext,namea+ mContext.getResources().getString(R.string.home_page_find_param_error_max_text) , Toast.LENGTH_SHORT).show();
//
//                            return;
//                        }
                        HomePages.mHomePages.setUpInfor(namea, mpinsEmptynfors, mEmptyType);
                    }

                    mEmptySetAdapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };
    private int mEmptyType = 0;
    private EmptyDataThread mEmptyDataThread = new EmptyDataThread();

    //上料跟排空
    private GridView frament_sets_infor_feed_item_gridvew = null;


    public EmptySetAdapter mEmptySetAdapter = null;
    public List<EmptySetData> mEmptySetData = null;

    public Button sets_fragment_layout_feed_button = null;
    public Button sets_fragment_layout_empty_button = null;


    //满料
    private GridView frament_sets_infor_material_item_gridvew = null;
    public MaterialSetAdapter mMaterialSetAdapter = null;
    public List<MaterialSetData> mMaterialSetData = null;

    //校验
    private GridView frament_sets_infor_check_item_gridvew = null;

    public CheckSetAdapter mCheckSetAdapter = null;
    public List<CheckSetData> mCheckSetData = null;

    private MyDatabaseInfor myDatabaseInfor = null;
    private SQLiteDatabase mBdread = null;
    private SQLiteDatabase mBdwrite = null;

    //清洗

    private ListView sets_bottom_clear_listvew = null;
    private List<ClearMenuItemData> mClearMenuItemData = null;
    private ClearMenuItemAdapter mClearMenuItemAdapter = null;

    //物理引脚
    private GridView frament_sets_infor_pin_item_gridvew = null;
    public PinsSetAdapter mPinsSetAdapter = null;
    public List<PinsSetData> mPinsSetData = null;
    private Map<String, Integer> materialsCapacity = new HashMap<>();
    private Map<Integer, Integer> materialsNumsCapacity = new HashMap<>();

    public SetsFragment() {

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup container, @NonNull Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sets_fragment_layout, container, false);
        mContext = view.getContext();
        myDatabaseInfor = new MyDatabaseInfor( mContext.getApplicationContext());
        mBdwrite = myDatabaseInfor.getWritableDatabase();
        mBdread = myDatabaseInfor.getReadableDatabase();

        sets_bottom_left_listvew = view.findViewById(R.id.sets_bottom_left_listvew);
        sets_bottom_right_clear_relative_layout = view.findViewById(R.id.sets_bottom_right_clear_relative_layout);
        sets_bottom_right_check_relative_layout = view.findViewById(R.id.sets_bottom_right_check_relative_layout);
        sets_bottom_right_material_relative_layout = view.findViewById(R.id.sets_bottom_right_material_relative_layout);
        sets_bottom_right_drain_relative_layout = view.findViewById(R.id.sets_bottom_right_drain_relative_layout);
        sets_bottom_right_pin_relative_layout = view.findViewById(R.id.sets_bottom_right_pin_relative_layout);
        sets_bottom_right_pwd_relative_layout = view.findViewById(R.id.sets_bottom_right_pwd_relative_layout);
        set_pwds_ok_btn = view.findViewById(R.id.set_pwds_ok_btn);
        set_pwds_ok_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String oldinfors ="";
                if( password_passwordedit_center_old_pwds !=  null ){
                    oldinfors =  password_passwordedit_center_old_pwds.getText().toString();
                }
                String newinfors1 ="";
                if( password_passwordedit_center_new_1_pwds !=  null ){
                    newinfors1 =  password_passwordedit_center_new_1_pwds.getText().toString();
                }
                String newinfors2 ="";
                if( password_passwordedit_center_new_2_pwds !=  null ){
                    newinfors2 =  password_passwordedit_center_new_2_pwds.getText().toString();
                }
                if(newinfors1.equals(newinfors2) &&  newinfors1.length() > 0){
                    if(oldinfors.equals( ConfigParams.getConfigParams().getPwds() )){
                        ConfigParams.getConfigParams().setPwds( newinfors1 );
                        ContentValues values = new ContentValues();

                        values.put("pwd", ConfigParams.getConfigParams().getPwds() );

                        long insert = mBdwrite.update("pwds", values, "verNumber=? ", new String[]{1 + "" });
                        Toast.makeText(mContext, mContext.getResources().getString(R.string.password_text_center_input_success_tip) , Toast.LENGTH_SHORT).show();

                    }else {
                        Toast.makeText(mContext, mContext.getResources().getString(R.string.password_text_center_input_error_tip) , Toast.LENGTH_SHORT).show();

                    }

                }else {
                    Toast.makeText(mContext, mContext.getResources().getString(R.string.password_text_center_input_error_one_tip) , Toast.LENGTH_SHORT).show();

                }


            }
        });
        password_passwordedit_center_old_pwds = view.findViewById(R.id.password_passwordedit_center_old_pwds);

        password_passwordedit_center_new_1_pwds = view.findViewById(R.id.password_passwordedit_center_new_1_pwds);

        password_passwordedit_center_new_2_pwds = view.findViewById(R.id.password_passwordedit_center_new_2_pwds);


        sets_bottom_left_listvew.setDivider(null);
        mSetsListLeftMenuAdapter = new SetsListLeftMenuAdapter(mContext, mSetsLeftMenuItemData);

        sets_bottom_left_listvew.setAdapter(mSetsListLeftMenuAdapter);


        sets_bottom_left_listvew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                LeftSetSelectindex.getLeftSelectindex().mLeftSelectIndex = position;

                mSetsListLeftMenuAdapter.notifyDataSetChanged();
                changeLeftMenuInfors();
            }
        });


        frament_sets_infor_feed_item_gridvew = view.findViewById(R.id.frament_sets_infor_feed_item_gridvew);
        mEmptySetData = new LinkedList<EmptySetData>();
        mEmptySetAdapter = new EmptySetAdapter(mContext, (LinkedList<EmptySetData>) mEmptySetData);
        if (frament_sets_infor_feed_item_gridvew != null) {
            frament_sets_infor_feed_item_gridvew.setAdapter(mEmptySetAdapter);
        }

        sets_fragment_layout_feed_button = view.findViewById(R.id.sets_fragment_layout_feed_button);
        sets_fragment_layout_feed_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mEmptyType = 0;
                mEmptyDataThread = new EmptyDataThread();
                mEmptyDataThread.start();
            }
        });
        sets_fragment_layout_empty_button = view.findViewById(R.id.sets_fragment_layout_empty_button);
        sets_fragment_layout_empty_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mEmptyType = 1;
                mEmptyDataThread = new EmptyDataThread();
                mEmptyDataThread.start();
            }
        });


        frament_sets_infor_material_item_gridvew = view.findViewById(R.id.frament_sets_infor_material_item_gridvew);


        mMaterialSetData = new LinkedList<MaterialSetData>();
        mMaterialSetAdapter = new MaterialSetAdapter(mContext, (LinkedList<MaterialSetData>) mMaterialSetData);
        if (frament_sets_infor_material_item_gridvew != null) {
            frament_sets_infor_material_item_gridvew.setAdapter(mMaterialSetAdapter);
        }

        frament_sets_infor_pin_item_gridvew = view.findViewById(R.id.frament_sets_infor_pin_item_gridvew);

        mPinsSetAdapter = null;

        mPinsSetData = new LinkedList<PinsSetData>();
        mPinsSetAdapter = new PinsSetAdapter(mContext, (LinkedList<PinsSetData>) mPinsSetData);
        if (frament_sets_infor_pin_item_gridvew != null) {
            frament_sets_infor_pin_item_gridvew.setAdapter(mPinsSetAdapter);
        }

        frament_sets_infor_check_item_gridvew = view.findViewById(R.id.frament_sets_infor_check_item_gridvew);

        mCheckSetData = new LinkedList<CheckSetData>();
        mCheckSetAdapter = new CheckSetAdapter(mContext, (LinkedList<CheckSetData>) mCheckSetData);
        if (frament_sets_infor_check_item_gridvew != null) {
            frament_sets_infor_check_item_gridvew.setAdapter(mCheckSetAdapter);
        }


        sets_bottom_clear_listvew = view.findViewById(R.id.sets_bottom_clear_listvew);
        sets_bottom_clear_listvew.setDivider(null);
        mClearMenuItemData = new LinkedList<ClearMenuItemData>();
        mClearMenuItemAdapter = new ClearMenuItemAdapter(mContext, (LinkedList<ClearMenuItemData>) mClearMenuItemData);
        if (sets_bottom_clear_listvew != null) {
            sets_bottom_clear_listvew.setAdapter(mClearMenuItemAdapter);
        }
        return view;
    }

    public void initLeftMenu(String infors, HashMap<Integer, Integer> mapa, HashMap<Integer, Float> pinSpeed) {
        mSetsLeftMenuItemData.clear();
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(1, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_one_text), ""));
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(2, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_two_text), ""));
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(3, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_three_text), ""));
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(4, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_four_text), ""));
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(5, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_five_text), ""));
        mSetsLeftMenuItemData.add(new SetsLeftMenuItemData(6, mContext.getResources().getString(R.string.set_list_content_bottom_btn_operation_six_text), ""));
        LeftSetSelectindex.getLeftSelectindex().mLeftSelectIndex = 0;
        if (mSetsListLeftMenuAdapter != null) {
            Log.d("bbb==", "13");
            mSetsListLeftMenuAdapter.notifyDataSetChanged();
            Log.d("bbb==", "14");
        }

        mEmptySetData.clear();
        mMaterialSetData.clear();
        mCheckSetData.clear();
        int numHeight = 0;

        try {
            JSONArray arry1 = new JSONArray(ContentInfor.getmUrlinfor().getInforAllMaterial());
            for (int j = 0; j < arry1.length(); j++) {
                JSONObject itema = arry1.getJSONObject(j);

                String name = itema.opt("name").toString();
                int max = 1000;

                if (!itema.isNull("max")) {
                    max = itema.optInt("max");
                }

                int min = 0;

                if (!itema.isNull("min")) {
                    min = itema.optInt("min");
                }

                String materialName = "";

                if (!itema.isNull("materialName")) {
                    materialName = itema.optString("materialName");
                }

                String materialTypeName = "";

                if (!itema.isNull("materialTypeName")) {
                    materialTypeName = itema.optString("materialTypeName");
                }
                materialsCapacity.put(name, max);
                int id = 0;

                if (!itema.isNull("id")) {
                    id = itema.optInt("id");
                }
                materialsNumsCapacity.put(id, max);
            }




            JSONArray arrysa = new JSONArray(ContentInfor.getmUrlinfor().getInforMaterial());

            for (int j = 0; j < arrysa.length(); j++) {
                JSONObject itema = arrysa.getJSONObject(j);
                int channelNumber = 0;

                if (itema.isNull("channelNumber")) {
                    continue;

                }
                channelNumber = itema.optInt("channelNumber");


                int preDischargeTime = 10;

                if (!itema.isNull("preDischargeTime")) {
                    preDischargeTime = itema.optInt("preDischargeTime");
                }
                int materiaId = 0;

                if (!itema.isNull("materiaId")) {
                    materiaId = itema.optInt("materiaId");
                }
                String materialName = "";

                if (!itema.isNull("materiaName")) {
                    materialName = itema.optString("materiaName");
                }

                String materialTypeName = "";

                if (!itema.isNull("materialTypeName")) {
                    materialTypeName = itema.optString("materialTypeName");
                }
                int max = 1000;

//                if (materialsCapacity.keySet().contains("max")) {
//                    max = materialsCapacity.get("max");
//                }
                if (materialsNumsCapacity.keySet().contains(materiaId)) {
                    max = materialsNumsCapacity.get(materiaId);
                }
                Log.d("aaa", "initLeftMenu: =" + itema.toString());
                String materialpins = String.valueOf(channelNumber);
                String materialFull = String.valueOf(max);
                String materialReserve1 = materialName;
                String materialReserve4 = String.valueOf(preDischargeTime);
                String materialReserve5 =  String.valueOf(preDischargeTime);
                String rack = "3000";
                String empty = "5000";
                String materialReserve6 ="";
                if (Integer.parseInt(materialpins) >= 1000) {
                    continue;
                }
//                if (materialReserve4.length() <= 0) {
//                    materialReserve4 = "10";
//                }
//                if (materialReserve5.length() <= 0) {
//                    materialReserve5 = "0";
//                }
                if (!isNumeric(materialReserve6)) {
                    materialReserve6 = "20";
                }

                // materialReserve4 ="2000";
                // materialReserve5 ="3000";
                mEmptySetData.add(new EmptySetData(Integer.parseInt(materialpins), materialReserve1, Integer.parseInt(rack), Integer.parseInt(empty), false));
                mMaterialSetData.add(new MaterialSetData(Integer.parseInt(materialpins), materialReserve1, materialFull));
                float speeda = 0;
                if (pinSpeed.keySet().contains(Integer.parseInt(materialpins))) {
                    speeda = pinSpeed.get(Integer.parseInt(materialpins));

                }

                mCheckSetData.add(new CheckSetData(Integer.parseInt(materialpins), materialReserve1, speeda, materialReserve5, Integer.parseInt(materialReserve6)));

                String pinb = String.valueOf(HomePages.mHomePages.getPinReal(Integer.parseInt(materialpins)));
                mPinsSetAdapter.add(new PinsSetData(Integer.parseInt(materialpins), materialReserve1, pinb));
                numHeight++;
            }
        } catch (JSONException e) {
            e.printStackTrace();

        }

        int lens1 = 0;
        lens1 = numHeight / 3;
        if ((numHeight % 3) > 0) {
            lens1++;
        }

        ViewGroup.LayoutParams layoutParams = frament_sets_infor_check_item_gridvew.getLayoutParams();// new LinearLayout.LayoutParams((int) mContext.getResources().getDimension(R.dimen.home_material_text_with), (int) mContext.getResources().getDimension(R.dimen.home_material_text_height));

        layoutParams.height = lens1 * (int) mContext.getResources().getDimension(R.dimen.speed_item_height);
        Log.d("aaa", "layoutParams.height ==" + String.valueOf(layoutParams.height));
        frament_sets_infor_check_item_gridvew.setLayoutParams(layoutParams);

        if (mEmptySetAdapter != null) {
            mEmptySetAdapter.notifyDataSetChanged();
        }


        if (mMaterialSetAdapter != null) {
            mMaterialSetAdapter.notifyDataSetChanged();
        }
        if (mPinsSetAdapter != null) {
            mPinsSetAdapter.notifyDataSetChanged();
        }


        if (mCheckSetAdapter != null) {
            mCheckSetAdapter.notifyDataSetChanged();
        }

        mClearMenuItemData.clear();
        try {
            if (ContentInfor.getmUrlinfor().getInforCleanTime().length() > 0) {


                JSONObject objcta = new JSONObject(ContentInfor.getmUrlinfor().getInforCleanTime());
                if (objcta.has("rows")) {
                    JSONArray devicematerial = objcta.optJSONArray("rows");
                    for (int j = 0; j < devicematerial.length(); j++) {
                        JSONObject itema = devicematerial.getJSONObject(j);
                        String cleantime_name = itema.optString("cleantime_name");
                        String cleantime_id = itema.optString("cleantime_id");
                        JSONArray children = itema.optJSONArray("children");
                        mClearMenuItemData.add(new ClearMenuItemData(Integer.parseInt(cleantime_id), cleantime_name, children.toString()));

                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();

        }

        if (mClearMenuItemAdapter != null) {
            mClearMenuItemAdapter.notifyDataSetChanged();
        }
        changeLeftMenuInfors();
    }

    public boolean isNumeric(String str) {
        return str.matches("\\d+"); // 匹配一个或多个数字
    }

    public void changeLeftMenuInfors() {
        Log.d("LeftSetSelectinde==", String.valueOf(LeftSetSelectindex.getLeftSelectindex().mLeftSelectIndex));
        if (LeftSetSelectindex.getLeftSelectindex().mLeftSelectIndex < 0) {
            return;
        }
        hideRelayout();
        switch (LeftSetSelectindex.getLeftSelectindex().mLeftSelectIndex) {
            case 0:
                if (sets_bottom_right_clear_relative_layout != null) {
                    sets_bottom_right_clear_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }

                break;
            case 1:
                if (sets_bottom_right_check_relative_layout != null) {
                    sets_bottom_right_check_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }

                break;
            case 2:
                if (sets_bottom_right_material_relative_layout != null) {
                    sets_bottom_right_material_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }

                break;
            case 3:
                if (sets_bottom_right_drain_relative_layout != null) {
                    sets_bottom_right_drain_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }

                break;
            case 4:
                if (sets_bottom_right_pin_relative_layout != null) {
                    sets_bottom_right_pin_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }

                break;

            case 5:
                if (sets_bottom_right_pwd_relative_layout != null) {
                    sets_bottom_right_pwd_relative_layout.setVisibility(RelativeLayout.VISIBLE);
                }
                if (password_passwordedit_center_old_pwds != null) {
                    password_passwordedit_center_old_pwds.setText("");
                }
                if (password_passwordedit_center_new_1_pwds != null) {
                    password_passwordedit_center_new_1_pwds.setText("");
                }
                if (password_passwordedit_center_new_2_pwds != null) {
                    password_passwordedit_center_new_2_pwds.setText("");
                }

                break;


        }
    }

    public void hideRelayout() {
        if (sets_bottom_right_clear_relative_layout != null) {
            sets_bottom_right_clear_relative_layout.setVisibility(RelativeLayout.GONE);
        }
        if (sets_bottom_right_check_relative_layout != null) {
            sets_bottom_right_check_relative_layout.setVisibility(RelativeLayout.GONE);
        }
        if (sets_bottom_right_material_relative_layout != null) {
            sets_bottom_right_material_relative_layout.setVisibility(RelativeLayout.GONE);
        }
        if (sets_bottom_right_drain_relative_layout != null) {
            sets_bottom_right_drain_relative_layout.setVisibility(RelativeLayout.GONE);
        }
        if (sets_bottom_right_pin_relative_layout != null) {
            sets_bottom_right_pin_relative_layout.setVisibility(RelativeLayout.GONE);
        }
        if (sets_bottom_right_pwd_relative_layout != null) {
            sets_bottom_right_pwd_relative_layout.setVisibility(RelativeLayout.GONE);
        }


    }


    //选中上料
    class EmptyDataThread extends Thread {
        @Override
        public void run() {

            mpinsEmptynfors.clear();
            for (int i = 0; i < mEmptySetData.size(); i++) {
                EmptySetData emptySetData = mEmptySetData.get(i);
                Log.d("aaa", "run:1=" + emptySetData.getMenuName());
                Log.d("aaa", "run:2=" + emptySetData.isSelectEd());
                Log.d("aaa", "run:2=" + emptySetData.getUpMaterils());
                Log.d("aaa", "run:3=" + emptySetData.getOutEmpty());
                if (emptySetData.isSelectEd()) {
                    if (mEmptyType == 0) {
                        mpinsEmptynfors.put(emptySetData.getMenuid(), emptySetData.getUpMaterils());

                    } else {
                        mpinsEmptynfors.put(emptySetData.getMenuid(), emptySetData.getOutEmpty());

                    }
                    emptySetData.setSelectEd(false);
                }
            }

            Message msg = new Message();
            msg.what = 1;  //消息(一个整型值)
            mTimeShowHandler.sendMessage(msg);
        }
    }
}
